package com.example.administrator.leargit.adapter;

import android.content.Context;
import android.content.pm.InstrumentationInfo;
import android.database.DataSetObserver;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ListView;

import com.example.administrator.leargit.bean.NewsBean;
import com.example.administrator.leargit.extra.ImageLoader;

import java.util.List;

/**
 * Created by Administrator on 2016/12/23 0023.
 */
public class NewAdapter extends BaseAdapter implements AbsListView.OnScrollListener {
    private final List<NewsBean> list;
    private final LayoutInflater inflater;
    private final ImageLoader mImageLoader;
    //用来保存滑动停止后，需要加载图片的开始位置和结束位置
    private int mStart, mEnd;
    //将List<NewsBean> 所有NewsBean 对象的newsPicUrl 转化静态数组存储在URLS中
    //这样在方便取得从mStart到mEnd之间的需要显示图片的url
    public static String[] URLS;
    private boolean mFirstIn;

    public NewAdapter(Context context, List<NewsBean> list, ListView listView) {
        this.list = list;
        inflater = LayoutInflater.from(context);
        mImageLoader = new ImageLoader(listView);
        URLS = new String[list.size()];
        //将List<NewsBean> 所有NewsBean 对象的newsPicUrl 转化静态数组存储在URLS中
        for (int i = 0; i < list.size(); i++) {
            URLS[i] = list.get(i).newsPicUrl;

        }
        mFirstIn = true;
        listView.setOnScrollListener(this);
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (scrollState == SCROLL_STATE_IDLE) {
            mImageLoader.loadImages(mStart, mEnd);
        } else {
            mImageLoader.cancelAllTask();
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        mStart = firstVisibleItem;
        mEnd = firstVisibleItem + visibleItemCount;
        //首次启动预加载，首次启动时，如果不滑动，onScrollStateChanged是不会执行的，但是可以执行onScroll方法，
        //故判断如果是第一次启动，并且ListView的Item已经绘制成功，即visiableItemCount>0，那么久先加载首屏的
        if (mFirstIn && visibleItemCount > 0) {
            mImageLoader.loadImages(mStart, mEnd);
            mFirstIn = false;
        }
    }

    @Override
    public void registerDataSetObserver(DataSetObserver observer) {
        super.registerDataSetObserver(observer);
    }

    @Override
    public int getCount() {
        return 0;
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        return null;
    }
}